import vec
import random
import pgzrun

IMG_SIZE = 160
SIZE = 3

WIDTH = IMG_SIZE * 3
HEIGHT = IMG_SIZE * 3

BACK_COLOR = (0, 0, 0)

images = {}
for i in range(1, 9):
    images[i] = Actor(str(i))

board = list(range(9))
random.shuffle(board)
print(board)

moving = False
startIndex = 0
endIndex = 0
startPos = vec.Vec2(0, 0)
endPos = vec.Vec2(0, 0)

for r in range(SIZE):
    for c in range(SIZE):
        x = c * IMG_SIZE + IMG_SIZE // 2
        y = r * IMG_SIZE + IMG_SIZE // 2
        num = board[r * SIZE + c]
        if num > 0:
            img = images[num]
            img.pos = x, y

def GetRowColFromIndex(idx):
    r = int(idx / SIZE)
    c = int(idx % SIZE)
    return r, c

def GetIndexFromRowCol(r, c):
    return r * SIZE + c

def GetRowColFromPos(pos):
    c = int(pos[0] / IMG_SIZE)
    r = int(pos[1] / IMG_SIZE)
    return r, c

def FindWay(r, c):
    global board
    if r + 1 < SIZE:
        idx = GetIndexFromRowCol(r + 1, c)
        if board[idx] == 0:
            return r + 1, c

    if r - 1 >= 0:
        idx = GetIndexFromRowCol(r - 1, c)
        if board[idx] == 0:
            return r - 1, c

    if c - 1 >= 0:
        idx = GetIndexFromRowCol(r, c - 1)
        if board[idx] == 0:
            return r, c - 1

    if c + 1 < SIZE:
        idx = GetIndexFromRowCol(r, c + 1)
        if board[idx] == 0:
            return r, c + 1

    return r, c


def onMoveFinished():
    global moving, board, startIndex, endIndex
    print('onMoveFinished')
    moving = False
    board[startIndex], board[endIndex] = board[endIndex], board[startIndex]

def on_mouse_up(pos):
    global startIndex, endIndex, moving, board, images
    print("mouse_up", pos)

    if moving == True:
        return

    r, c = GetRowColFromPos(pos)
    rr, cc = FindWay(r, c)
    if rr != r or cc != c:
        moving = True
        startIndex = GetIndexFromRowCol(r, c)
        endIndex = GetIndexFromRowCol(rr, cc)
        num = board[startIndex]
        endPos.x = cc * IMG_SIZE + IMG_SIZE // 2
        endPos.y = rr * IMG_SIZE + IMG_SIZE // 2
        animate(images[num], pos = (endPos.x, endPos.y), duration = 0.5, tween = 'decelerate', on_finished = onMoveFinished)

def update():
    pass

def draw():
    screen.fill(BACK_COLOR) 

    for v in images.values():
        v.draw()

pgzrun.go()